/**
 * Copyright (C) 2013 Oleg Anastassov <oleg.anastassov@gmail.com>
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package kz.kstu.loc.business.extract.strategy;

import kz.kstu.loc.entity.Item;
import kz.kstu.loc.util.StringUtils;
import kz.kstu.loc.util.logger.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellReference;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Date: 17.01.2013
 * Time: 16:50
 *
 * @author Oleg Anastassov
 */
public class ExcelExtractStrategy implements ExtractStrategy {

    private static final Logger LOGGER = Logger.getLogger(ExcelExtractStrategy.class);

    public ExcelExtractStrategy() {
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<Item> extract(File file) {
        InputStream is = null;
        Workbook wb = null;
        try {
            is = new FileInputStream(file);
            wb = new HSSFWorkbook(is);

        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
        // TODO: Не исключена возможность, что листа в книге может не оказаться.
        // TODO: Может упаться NullPointerException.
        Sheet sheet = wb.getSheetAt(0);

        List<Item> items = new ArrayList<Item>();
        for (Row row : sheet) {
            if (isEmptyRow(row)) {
                continue;
            }

            Item item = new Item();
            for (Cell cell : row) {
                // пропускаем строку заголовка
                if (cell.getRowIndex() == 0) {
                    break;
                }

                try {
                    switch (cell.getColumnIndex()) {
                        case 0: // ключ
                            String key = getStringValue(cell);
                            item.setKey(key);
                            break;
                        case 1: // значение на русском
                            String valueRus = getStringValue(cell);
                            item.setValueRus(valueRus);
                            break;
                        case 2: // значение на казахском
                            String valueKaz = getStringValue(cell);
                            item.setValueKaz(valueKaz);
                            break;
                    }
                } catch (Exception e) {
                    throw new IllegalArgumentException(
                            "Ошибка чтения. Неверный формат ячейки \""
                                    + getCellAddress(cell) + "\"", e
                    );
                }
            }
            if (row.getRowNum() != 0) {
                items.add(item);
            }
        }
        return items;
    }

    private String getCellAddress(Cell cell) {
        CellReference cellRef = new CellReference(cell.getRow().getRowNum(), cell.getColumnIndex());
        return cellRef.formatAsString();
    }

    private boolean isEmptyRow(Row row) {
        for (Cell cell : row) {
            if (cell.getCellType() != Cell.CELL_TYPE_BLANK) {
                return false;
            }
        }
        return true;
    }

    private String getStringValue(Cell cell) {
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                return cell.getStringCellValue();
            case Cell.CELL_TYPE_BLANK:
                return StringUtils.EMPTY_STRING;
            default:
                LOGGER.error("Illegal cell type. Cell={0}", cell);
                throw new IllegalArgumentException("Ошибка типа ячейки.");
        }
    }

}
